﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 学生管理
{
    public partial class FormShow : Form
    {
        public FormShow()
        {
            InitializeComponent();
            DownloadFile("http://123.123.123.123/Image/123.docx", @"D:\123.cm", progressBar1, label1);
        }

        private void Btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }



        public void DownloadFile(string URL, string fliename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            try
            {

                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);//请求URL的文件
                System.Net.HttpWebResponse myrq = (System.Net.HttpWebResponse)Myrq.GetResponse();//获取请求得到的文件
                long totalBytes = myrq.ContentLength;//采用流方式读取文件
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;//给进度条赋值
                }
                System.IO.Stream st = myrq.GetResponseStream();//Stream是一个抽象类 表示一切以“流”的方式读写数据操作的集合。
                //FileStream类继承自Stream类，一个FileStream实例，代表一个文件流，用于对磁盘文件进行读取、写入、打开、关闭等操作。
                System.IO.Stream so = new System.IO.FileStream(fliename, System.IO.FileMode.Create);

                long totalDownloadByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadByte = osize + totalDownloadByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);
                    float precent = 0;
                    precent = (float)totalDownloadByte / (float)totalBytes * 100;
                    label1.Text = "当前下载进度" + precent.ToString() + "%";
                    System.Windows.Forms.Application.DoEvents();//必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }

        }
    }
}
